/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mrp.persistencia.controller;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import mrp.persistencia.entity.Materiaprima;
import mrp.persistencia.entity.Tallatacosuela;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;
import mrp.beans.util.EntityManagerUtil;
import mrp.persistencia.controller.exceptions.IllegalOrphanException;
import mrp.persistencia.controller.exceptions.NonexistentEntityException;
import mrp.persistencia.controller.exceptions.PreexistingEntityException;
import mrp.persistencia.controller.exceptions.RollbackFailureException;
import mrp.persistencia.entity.Tacosuela;

/**
 *
 * @author root
 */
public class TacosuelaJpaController implements Serializable {

    public TacosuelaJpaController() {
        
        this.emf = EntityManagerUtil.getEntityManagerFactory();
    }

    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Tacosuela tacosuela) throws IllegalOrphanException, PreexistingEntityException, RollbackFailureException, Exception {
        if (tacosuela.getTallatacosuelaList() == null) {
            tacosuela.setTallatacosuelaList(new ArrayList<Tallatacosuela>());
        }
        List<String> illegalOrphanMessages = null;
//        Materiaprima materiaprimaOrphanCheck = tacosuela.getMateriaprima();
//        if (materiaprimaOrphanCheck != null) {
//            Tacosuela oldTacosuelaOfMateriaprima = materiaprimaOrphanCheck.getTacosuela();
//            if (oldTacosuelaOfMateriaprima != null) {
//                if (illegalOrphanMessages == null) {
//                    illegalOrphanMessages = new ArrayList<String>();
//                }
//                illegalOrphanMessages.add("The Materiaprima " + materiaprimaOrphanCheck + " already has an item of type Tacosuela whose materiaprima column cannot be null. Please make another selection for the materiaprima field.");
//            }
//        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
//            Materiaprima materiaprima = tacosuela.getMateriaprima();
//            if (materiaprima != null) {
//                materiaprima = em.getReference(materiaprima.getClass(), materiaprima.getCodmateriaprima());
//                tacosuela.setMateriaprima(materiaprima);
//            }
           /* List<Tallatacosuela> attachedTallatacosuelaList = new ArrayList<Tallatacosuela>();
            for (Tallatacosuela tallatacosuelaListTallatacosuelaToAttach : tacosuela.getTallatacosuelaList()) {
                tallatacosuelaListTallatacosuelaToAttach = em.getReference(tallatacosuelaListTallatacosuelaToAttach.getClass(), tallatacosuelaListTallatacosuelaToAttach.getCodtallatacosuela());
                attachedTallatacosuelaList.add(tallatacosuelaListTallatacosuelaToAttach);
            }*/
            //tacosuela.setTallatacosuelaList(attachedTallatacosuelaList);
            em.persist(tacosuela);
//            if (materiaprima != null) {
//                materiaprima.setTacosuela(tacosuela);
//                materiaprima = em.merge(materiaprima);
//            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findTacosuela(tacosuela.getCodmateriaprima()) != null) {
                throw new PreexistingEntityException("Tacosuela " + tacosuela + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Tacosuela tacosuela) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            Tacosuela persistentTacosuela = em.find(Tacosuela.class, tacosuela.getCodmateriaprima());
//            Materiaprima materiaprimaOld = persistentTacosuela.getMateriaprima();
//            Materiaprima materiaprimaNew = tacosuela.getMateriaprima();
            List<Tallatacosuela> tallatacosuelaListOld = persistentTacosuela.getTallatacosuelaList();
            List<Tallatacosuela> tallatacosuelaListNew = tacosuela.getTallatacosuelaList();
            List<String> illegalOrphanMessages = null;
//            if (materiaprimaNew != null && !materiaprimaNew.equals(materiaprimaOld)) {
//                Tacosuela oldTacosuelaOfMateriaprima = materiaprimaNew.getTacosuela();
//                if (oldTacosuelaOfMateriaprima != null) {
//                    if (illegalOrphanMessages == null) {
//                        illegalOrphanMessages = new ArrayList<String>();
//                    }
//                    illegalOrphanMessages.add("The Materiaprima " + materiaprimaNew + " already has an item of type Tacosuela whose materiaprima column cannot be null. Please make another selection for the materiaprima field.");
//                }
//            }
            
            for (int i=0;i<tallatacosuelaListOld.size();i++) {
                boolean esDeEliminar=true;
                for (int j=0;j<tallatacosuelaListNew.size();j++) {
                    if (tallatacosuelaListNew.get(j).equals(tallatacosuelaListOld.get(i)))
                     {
                         esDeEliminar=false;
                         break;                       
                    }
                }
                if(esDeEliminar)
                {
                    Tallatacosuela ttsEliminar=em.find(Tallatacosuela.class, tallatacosuelaListOld.get(i).getCodtallatacosuela());                   
                    em.remove(ttsEliminar);
                }
            }
//            for (Tallatacosuela tallatacosuelaListOldTallatacosuela : tallatacosuelaListOld) {
//                if (!tallatacosuelaListNew.contains(tallatacosuelaListOldTallatacosuela)) {
//                    tallatacosuelaListNew.
////                    if (illegalOrphanMessages == null) {
////                        illegalOrphanMessages = new ArrayList<String>();
////                    }
////                    illegalOrphanMessages.add("You must retain Tallatacosuela " + tallatacosuelaListOldTallatacosuela + " since its tacosuelaFk field is not nullable.");
//                }
//            }
//            if (illegalOrphanMessages != null) {
//                throw new IllegalOrphanException(illegalOrphanMessages);
//            }
//            if (materiaprimaNew != null) {
//                materiaprimaNew = em.getReference(materiaprimaNew.getClass(), materiaprimaNew.getCodmateriaprima());
//                tacosuela.setMateriaprima(materiaprimaNew);
//            }
//            List<Tallatacosuela> attachedTallatacosuelaListNew = new ArrayList<Tallatacosuela>();
//            for (Tallatacosuela tallatacosuelaListNewTallatacosuelaToAttach : tallatacosuelaListNew) {
//                tallatacosuelaListNewTallatacosuelaToAttach = em.getReference(tallatacosuelaListNewTallatacosuelaToAttach.getClass(), tallatacosuelaListNewTallatacosuelaToAttach.getCodtallatacosuela());
//                attachedTallatacosuelaListNew.add(tallatacosuelaListNewTallatacosuelaToAttach);
//            }
//            tallatacosuelaListNew = attachedTallatacosuelaListNew;
//            tacosuela.setTallatacosuelaList(tallatacosuelaListNew);
            tacosuela = em.merge(tacosuela);
//            if (materiaprimaOld != null && !materiaprimaOld.equals(materiaprimaNew)) {
//                materiaprimaOld.setTacosuela(null);
//                materiaprimaOld = em.merge(materiaprimaOld);
//            }
//            if (materiaprimaNew != null && !materiaprimaNew.equals(materiaprimaOld)) {
//                materiaprimaNew.setTacosuela(tacosuela);
//                materiaprimaNew = em.merge(materiaprimaNew);
//            }
            
            for (Tallatacosuela tallatacosuelaListNewTallatacosuela : tallatacosuelaListNew) {
                if (!tallatacosuelaListOld.contains(tallatacosuelaListNewTallatacosuela)) {
                    Tacosuela oldTacosuelaFkOfTallatacosuelaListNewTallatacosuela = tallatacosuelaListNewTallatacosuela.getTacosuelaFk();
                    tallatacosuelaListNewTallatacosuela.setTacosuelaFk(tacosuela);
                    tallatacosuelaListNewTallatacosuela = em.merge(tallatacosuelaListNewTallatacosuela);
                    if (oldTacosuelaFkOfTallatacosuelaListNewTallatacosuela != null && !oldTacosuelaFkOfTallatacosuelaListNewTallatacosuela.equals(tacosuela)) {
                        oldTacosuelaFkOfTallatacosuelaListNewTallatacosuela.getTallatacosuelaList().remove(tallatacosuelaListNewTallatacosuela);
                        oldTacosuelaFkOfTallatacosuelaListNewTallatacosuela = em.merge(oldTacosuelaFkOfTallatacosuelaListNewTallatacosuela);
                    }
                }
            }
            
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = tacosuela.getCodmateriaprima();
                if (findTacosuela(id) == null) {
                    throw new NonexistentEntityException("The tacosuela with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
           
            em = getEntityManager(); 
            em.getTransaction().begin();
            Tacosuela tacosuela;
            try {
                tacosuela = em.getReference(Tacosuela.class, id);
                tacosuela.getCodmateriaprima();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The tacosuela with id " + id + " no longer exists.", enfe);
            }
//            List<String> illegalOrphanMessages = null;
//            List<Tallatacosuela> tallatacosuelaListOrphanCheck = tacosuela.getTallatacosuelaList();
//            for (Tallatacosuela tallatacosuelaListOrphanCheckTallatacosuela : tallatacosuelaListOrphanCheck) {
//                if (illegalOrphanMessages == null) {
//                    illegalOrphanMessages = new ArrayList<String>();
//                }
//                illegalOrphanMessages.add("This Tacosuela (" + tacosuela + ") cannot be destroyed since the Tallatacosuela " + tallatacosuelaListOrphanCheckTallatacosuela + " in its tallatacosuelaList field has a non-nullable tacosuelaFk field.");
//            }
//            if (illegalOrphanMessages != null) {
//                throw new IllegalOrphanException(illegalOrphanMessages);
//            }
//            Materiaprima materiaprima = tacosuela.getMateriaprima();
//            if (materiaprima != null) {
//                materiaprima.setTacosuela(null);
//                materiaprima = em.merge(materiaprima);
//            }
            em.remove(tacosuela);
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Tacosuela> findTacosuelaEntities() {
        return findTacosuelaEntities(true, -1, -1);
    }

    public List<Tacosuela> findTacosuelaEntities(int maxResults, int firstResult) {
        return findTacosuelaEntities(false, maxResults, firstResult);
    }

    private List<Tacosuela> findTacosuelaEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Tacosuela.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Tacosuela findTacosuela(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Tacosuela.class, id);
        } finally {
            em.close();
        }
    }

    public int getTacosuelaCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Tacosuela> rt = cq.from(Tacosuela.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    public List<Tacosuela> findTacosuelaWhereOrderBy(String consulta,boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
//            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
//            cq.select(cq.from(Cliente.class));
//            Query q = em.createQuery(cq);
//            Query q = em.createQuery("SELECT o FROM Cliente o where "+ +" order by o.numerocliente");
            Query q = em.createQuery(consulta);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }
}
